#include <stdio.h>
#include <stdint.h>
#include "uart.h"

void UART_Init(uint32_t baudRate)
{
	/* Initialize the gpio(s) of the usart */
	GPIO_InitType GPIO_InitStruct;
	
	RCC_EnableAPB2PeriphClk(UART_GPIO_PORT_CLK | RCC_APB2_PERIPH_AFIO, ENABLE);
	
	GPIO_InitStruct.Pin        = UART_TX_GPIO_PIN;
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStruct.GPIO_Mode  = GPIO_Mode_AF_PP;
	GPIO_InitPeripheral(UART_GPIO_PORT, &GPIO_InitStruct);

	GPIO_InitStruct.Pin       = UART_RX_GPIO_PIN;
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_InitPeripheral(UART_GPIO_PORT, &GPIO_InitStruct);
	
	/* Initialize the the usart */
	USART_InitType USART_InitStruct;
	
	RCC_EnableAPB2PeriphClk(UART_CLOCK, ENABLE);
	
	USART_InitStruct.BaudRate = baudRate;
	USART_InitStruct.HardwareFlowControl = USART_HFCTRL_NONE;
	USART_InitStruct.Mode = USART_MODE_RX | USART_MODE_TX;
	USART_InitStruct.Parity = USART_PE_NO;
	USART_InitStruct.StopBits = USART_STPB_1;
	USART_InitStruct.WordLength = USART_WL_8B;
	USART_Init(UART_USED, &USART_InitStruct);
	USART_Enable(UART_USED, ENABLE);
}

/* retarget the C library printf function to the USART */
int fputc(int ch, FILE* f)
{
	assert_param((UART_USED == USART1) || (UART_USED == USART2) || (UART_USED == USART3) || (UART_USED == USART4));
	
	UART_USED ->DAT = ch;
	while (USART_GetFlagStatus(UART_USED, USART_FLAG_TXC) != SET)
	{
		;
	}
	return (ch);
}
